package com.tusuo.stds.ui.questionbank;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.tusuo.stds.R;
import com.tusuo.stds.rest.LevelDetail;
import com.tusuo.stds.rest.Question;
import com.tusuo.stds.rest.QuestionBankGroup;
import com.tusuo.stds.rest.QuestionBankList;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.draft.DraftActivity_;
import com.tusuo.stds.ui.question.QuestionAdapterForQuestionBank;
import com.tusuo.stds.ui.similarity.SimilarityTempActivity;
import com.tusuo.stds.util.Utils;
import com.tusuo.stds.util.webview.WebViewManager;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcels;

import java.util.ArrayList;
import java.util.List;

import myandroid.library.util.ApplicationHelper;
import rx.functions.Action0;

import static com.tusuo.stds.ui.question.QuestionActivity.QUESTION_TYPE_MULTI;
import static com.tusuo.stds.ui.question.QuestionActivity.QUESTION_TYPE_SINGLE;
import static com.tusuo.stds.ui.question.QuestionActivity.QUESTION_TYPE_TF;
import static com.tusuo.stds.ui.question.QuestionActivity.QUESTION_TYPE_UNSURE;

@EActivity(R.layout.activity_question_bank_temp)
public class QuestionBankTempActivity extends BaseToolbarActivity<QuestionBankTempView,QuestionBankTempPresenter> implements QuestionBankTempView,ViewPager.OnPageChangeListener {


    @ViewById(R.id.question_bank_temp_btn_answer)
    RadioButton btnAnswer;
    @ViewById(R.id.question_bank_temp_btn_recite)
    RadioButton btnRecite;
    @ViewById(R.id.question_bank_temp_indicator_answer)
    View indicatorAnswer;
    @ViewById(R.id.question_bank_temp_indicator_recite)
    View indicatorRecite;

    @ViewById(R.id.question_bank_temp_group)
    RadioGroup rgGroup;

    @ViewById(R.id.question_bank_temp_tv_question_type)
    TextView tvType;

    @ViewById(R.id.question_bank_temp_vp_answer)
    ViewPager vpAnswer;

    @ViewById(R.id.question_bank_temp_layout_bin)
    LinearLayout layoutDelete;
    @ViewById(R.id.question_bank_temp_layout_settings)
    LinearLayout layoutSetting;
    @ViewById(R.id.question_bank_temp_layout_count)
    LinearLayout layoutCount;
    @ViewById(R.id.question_bank_temp_layout_main)
    LinearLayout layoutMain;
    @ViewById(R.id.question_bank_temp_layout_no_question)
    RelativeLayout layoutNoQuestion;

    @ViewById(R.id.question_bank_temp_tv_correct_count)
    TextView tvRight;
    @ViewById(R.id.question_bank_temp_tv_wrong_count)
    TextView tvWrong;
    @ViewById(R.id.question_bank_temp_tv_total_count)
    TextView tvCount;


    @StringRes(R.string.toolbar_title_question_bank)
    String toolbarTitle;
    @StringRes(R.string.question_type_single)
    String strTypeSingle;
    @StringRes(R.string.question_type_multi)
    String strTypeMulti;
    @StringRes(R.string.question_type_tf)
    String strTypeTF;
    @StringRes(R.string.question_type_unsure)
    String strTypeUnsure;

    private QuestionBankList mQuestionBankList;
    private int currentType = 0;    // 0　做题模式   1   阅题模式

    int mQuestionSettingCorrectCount;

    private List<WebViewManager> mAnswerWebViewManagerList = new ArrayList<>();
    private List<View> answerListView = new ArrayList<>();
    private List<Question> mQuestionList = new ArrayList<>();

    String mSecretKey;
    private SettingsTransparentTempDialog mSettingsDialog;
    private QuestionAdapterForQuestionBank answerAdapter2;
    private LevelDetail detail = new LevelDetail();
    private QuestionBankGroup mQuestionBankGroup;
    private QuestionBankBottomTransparentDialog mQuestionBankCountDialog;
    private int mWrongQuestionId;

    private boolean isSelected = false;
    private List<Question> data;
    private List<String> answerContents = new ArrayList<>();
    private int mSelectId = -1;
    private String mIds;
    private boolean firstSelected = true;
    private List<Integer> mDataId;
    private boolean dataOrder = false;

    @AfterInject
    void init() {
        mDataId = new ArrayList<>();
        mQuestionBankList = Parcels.unwrap(getIntent().getParcelableExtra(QuestionBankList.EXTRA_NAME));
        if (mQuestionList != null) {
            StringBuilder builder = new StringBuilder();
            for (Integer integer : mQuestionBankList.Data) {
                mDataId.add(integer);
                builder.append(integer);
                if (mQuestionBankList.Data.indexOf(integer) != mQuestionBankList.Total - 1) {
                    builder.append(",");
                }
            }
            mIds = builder.toString();
        }
    }

    @AfterViews
    void initData() {

        setupUI(this);

        List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();

        ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction("草稿", new Action0() {
            @Override
            public void call() {
                startActivity(new Intent(QuestionBankTempActivity.this, DraftActivity_.class));
            }
        }, 0);

        menuActionList.add(menuAction);

        ToolbarOwner.Config config = new ToolbarOwner.Config(toolbarTitle, true, menuActionList);
        mToolbarOwner.setConfig(config);

        btnAnswer.setChecked(true);
        btnRecite.setChecked(false);
        rgGroup.setVisibility(View.INVISIBLE);
        indicatorAnswer.setVisibility(View.VISIBLE);
        indicatorRecite.setVisibility(View.INVISIBLE);

        vpAnswer.addOnPageChangeListener(this);
        vpAnswer.setOffscreenPageLimit(2);

        ApplicationHelper.getInstance().addActivity(this);

        if (mDataId.size() <= 0) {
            showNoQuestion();
        }else {
            mWrongQuestionId = mDataId.get(0);
            rgGroup.setVisibility(View.VISIBLE);
        }

        loadData();

    }

    @Override
    @UiThread
    public void initAdapter(List<Question> data) {

        if (!dataOrder) {
            loadQuestion(data);
        }else {
            List<Question> tempData = new ArrayList<>();
            for (int i = mIndex; i < mIndex + data.size() ; i ++) {
                for (int j = 0; j < data.size() ; j ++) {
                    if (data.get(j).Id == mDataId.get(i)) {
                        tempData.add(data.get(j));
                    }
                }
            }

            loadQuestion(tempData);
        }
    }

    public void initContent() {
        for (int i = 0 ; i < data.size() ; i ++) {
            Question question = data.get(i);
            question.Text = question.getDecodedText(mSecretKey);
            question.QuestionAnalysis = question.getDecodedQuestionAnalysis(mSecretKey);
            for (Question.QuestionOption option : question.QuestionOptionList) {
                option.Content = option.getDecodedContent(mSecretKey);
            }
        }
    }

    @Click(R.id.question_bank_temp_btn_answer)
    void changeAnswer() {
        btnAnswer.setChecked(true);
        btnRecite.setChecked(false);
        indicatorAnswer.setVisibility(View.VISIBLE);
        indicatorRecite.setVisibility(View.INVISIBLE);
        currentType = 0;
        answerAdapter2.setQuestionMode(0);
        loadAnswerQuestion();
    }

    @Click(R.id.question_bank_temp_btn_recite)
    void changeRecite() {
        btnAnswer.setChecked(false);
        btnRecite.setChecked(true);
        indicatorAnswer.setVisibility(View.INVISIBLE);
        indicatorRecite.setVisibility(View.VISIBLE);
        answerAdapter2.setQuestionMode(1);

        currentType = 1;
        loadReciteQuestion();
    }

    @Click(R.id.question_bank_temp_layout_settings)
    void clickSettingsBtn() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        if (mSettingsDialog != null) {
            mSettingsDialog.dismiss();
            mSettingsDialog = null;
        }

        mSettingsDialog = new SettingsTransparentTempDialog(this, presenter);
        mSettingsDialog.show();
    }

    @Click(R.id.question_bank_temp_layout_bin)
    void clickBinBtn() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        if (data.size() == 0) {
            return;
        }

        int index = vpAnswer.getCurrentItem();

        mWrongQuestionId = mQuestionList.get(index).Id;
        if ( mWrongQuestionId != 0) {
            presenter.removeWrongQuestion(mWrongQuestionId);
            answerListView.remove(index);
            mAnswerWebViewManagerList.remove(index);

            for (int i = 0; i < mQuestionBankGroup.Data.size();i ++) {
                QuestionBankGroup.QuestionGroup group = mQuestionBankGroup.Data.get(i);
                for (int j = 0; j < group.List.size(); j ++) {
                    if (mWrongQuestionId == group.List.get(j)) {
                        if (group.List.size() > 1) {
                            group.List.remove(j);
                        } else {
                            mQuestionBankGroup.Data.remove(i);
                        }
                        break;
                    }
                }
            }

            answerContents.remove(index);
            mQuestionList.remove(index);
            mDataId.remove(index);
            data.remove(index);
//            detail.QuestionList.remove(index);
            detail.QuestionCount --;


        }
        Utils.UI.showToastShort("错题已移除");

        if (data.size() > 0) {
            answerAdapter2.notifyDataSetChanged();
            tvCount.setText(getString(R.string.question_count, vpAnswer.getCurrentItem() + 1, data.size()));
        }else {
            showNoQuestion();
        }
    }

    @NonNull
    @Override
    public QuestionBankTempPresenter createPresenter() {
        return new QuestionBankTempPresenter(this);
    }

    private void showNoQuestion() {
        layoutMain.setVisibility(View.GONE);
        layoutNoQuestion.setVisibility(View.VISIBLE);
    }

    private void loadAnswerQuestion() {
        int currentItem = vpAnswer.getCurrentItem();
        if (!TextUtils.isEmpty(answerContents.get(currentItem))) {
            answerAdapter2.setAnswerContent(currentItem,answerContents.get(currentItem));
            answerAdapter2.setAnswerContentReviewMode(currentItem);
        }else {
            if (currentItem > 0) {
                answerAdapter2.setAnswerMode(currentItem,answerContents);
                answerAdapter2.setAnswerMode(currentItem - 1,answerContents);
                if (currentItem < mQuestionList.size() - 1) {
                    answerAdapter2.setAnswerMode(currentItem + 1,answerContents);
                }
            }else {
                answerAdapter2.setAnswerMode(currentItem,answerContents);
                if (currentItem < mQuestionList.size() - 1) {
                    answerAdapter2.setAnswerMode(currentItem + 1,answerContents);
                }
            }
        }
    }

    private void loadReciteQuestion() {
        int currentItem = vpAnswer.getCurrentItem();
        answerAdapter2.setReviewMode(currentItem);
        if (currentItem < mQuestionList.size() - 1) {
            answerAdapter2.setReviewMode(currentItem + 1);
        }
    }

    void loadData() {

        mQuestionList = new ArrayList<>();
        mAnswerWebViewManagerList = new ArrayList<>();
        answerListView = new ArrayList<>();
        answerContents = new ArrayList<>();
        data = new ArrayList<>();

        for (int i = 0; i < mDataId.size(); i ++) {
            data.add(null);
            answerContents.add("");
            answerListView.add(null);
            mAnswerWebViewManagerList.add(null);
            mQuestionList.add(null);
        }

        loadOtherQuestion(0);
    }



    @Override
    public void setSecretKey(String secretKey) {
        mSecretKey = secretKey;

    }

    @Override
    public void setQuestionSetting(int questionSettingCorrectCount) {
        mQuestionSettingCorrectCount = questionSettingCorrectCount;

    }

    @Override
    public void setQuestionBankGroup(QuestionBankGroup questionBankGroup) {
        if (questionBankGroup.Data.size() > 0) {
            this.mQuestionBankGroup = questionBankGroup;
        }else {
            showNoQuestion();
        }
//        presenter.getQuestionBankContent(false,true,mIds,-1);
    }

    @Override
    public void initFirst() {

    }

    @Override
    public void toNextQuestion(int correctCount, int wrongCount) {
        int currentItem = vpAnswer.getCurrentItem();
        tvRight.setText(correctCount + "");
        tvWrong.setText(wrongCount + "");

        if (presenter.getQuestionSettingCorrectCount() == correctCount) {
            clickBinBtn();
        }else {
            Question question = mQuestionList.get(currentItem);
            question.CorrectCount = correctCount;
            question.WrongCount = wrongCount;
            if (currentItem == mDataId.size() - 1) {
                answerAdapter2.setAnswerMode(currentItem,answerContents);
                answerAdapter2.setAnswerContentReviewModeRepeat(currentItem);
            }
            handler.sendEmptyMessageDelayed(123,1500);
        }

    }



    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        isSelected = false;
        isAnswerSubmit = false;
    }

    @Override
    public void onPageSelected(int position) {

    }
    private boolean isAnswerSubmit = false;

    private int mQuestionListSize = 0;

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_IDLE) {
            int currentItem = vpAnswer.getCurrentItem();
            if (mQuestionList.get(currentItem) == null) {
                // 说明之前的数据没有加载
                loadOtherQuestion(currentItem);
            }else {
                initText(mQuestionList.get(currentItem),currentItem);
            }


            if (Math.abs(currentItem + 1 - (currentItem / 50 + 1) * 50) <= 10 && mQuestionListSize <= (currentItem / 50 + 1) * 50 && mQuestionListSize < data.size()) {
                loadNextQuestion(currentItem);
            }

            if (!isAnswerSubmit) {
                currentIndex = currentItem;
            }

            if (currentType == 0) {
                if (currentItem == currentIndex) {
                    if (isAnswerSubmit) {
                        answerAdapter2.setAnswerContentReviewModeRepeat(currentItem - 1);
                        if (currentItem < mQuestionList.size() - 1) {
                            answerAdapter2.setAnswerModeRepeat(currentItem + 1);
                        }
                        if (currentItem < answerAdapter2.getWebViewManagerSize()) {
                            if (!TextUtils.isEmpty(answerContents.get(currentItem))) {
                                answerAdapter2.setAnswerMode(currentItem,answerContents);
                            }
                        }
                    }else {
                        loadAnswerQuestion();
                    }
                }
            }else {
                if (currentItem < answerAdapter2.getWebViewManagerSize()) {
                    if (!TextUtils.isEmpty(answerContents.get(currentItem))) {
                        answerAdapter2.setReviewMode(currentItem);
                    }else {
                        if (currentItem < mQuestionList.size() - 1) {
                            answerAdapter2.setAnswerContentReviewModeRepeat(currentItem + 1);
                        }
                        answerAdapter2.setAnswerContentReviewModeRepeat(currentItem);
                    }

                }
            }
        }

    }

    public void initText(Question question,int index) {
        switch (question.QuestionType) {
            case QUESTION_TYPE_SINGLE:
                tvType.setText(strTypeSingle);
                break;
            case QUESTION_TYPE_MULTI:
                tvType.setText(strTypeMulti);
                break;
            case QUESTION_TYPE_TF:
                tvType.setText(strTypeTF);
                break;
            case QUESTION_TYPE_UNSURE:
                tvType.setText(strTypeUnsure);
                break;
            default:
                tvType.setText("未知");
                break;
        }
        tvCount.setText(getString(R.string.question_count, index + 1, data.size()));
        tvRight.setText(question.CorrectCount+"");
        tvWrong.setText(question.WrongCount+"");

    }

    @Click(R.id.question_bank_temp_layout_count)
    void showListDialog() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        if (mQuestionBankGroup == null) {
            Utils.UI.showToastShort("错题分组数据载入中，请稍等片刻");
        }

        if (mQuestionBankCountDialog != null) {
            mQuestionBankCountDialog.dismiss();
            mQuestionBankCountDialog = null;
        }

        mWrongQuestionId = mQuestionList.get(vpAnswer.getCurrentItem()).Id;

        mQuestionBankCountDialog = new QuestionBankBottomTransparentDialog(this,
                tvCount.getText().toString(),
                tvRight.getText().toString(),
                tvWrong.getText().toString(),
                mQuestionBankGroup,
                mWrongQuestionId);
        mQuestionBankCountDialog.show();
    }


    public void showCertainQuestion(int selectedId) {
        mSelectId = selectedId;

        if (firstSelected) {
            loadOrderQuestion();
        }else {
            showCertainQuestion();
        }

    }

    public void loadOrderQuestion() {
        mDataId = new ArrayList<>();
        for (int k = 0; k < mQuestionBankGroup.Total ; k ++) {
            for (int l = 0; l < mQuestionBankGroup.Data.get(k).List.size(); l ++) {
                mDataId.add(mQuestionBankGroup.Data.get(k).List.get(l));
            }
        }
        dataOrder = true;

        loadData();

    }

    public void showCertainQuestion() {
        if (mSelectId == -1) {
            return;
        }

        int index = -1;
        int indexTemp = -1;

        List<Question> tempList = mQuestionList;

        for (int i = 0; i < mDataId.size();i ++) {
            if (mSelectId == mDataId.get(i)) {
                indexTemp = i;
                // 在所有问题列表中是存在的
                for (int j = 0; j < tempList.size(); j ++) {
                    if (tempList.get(j) != null ) {
                        if (tempList.get(j).Id == mSelectId) {
                            index = j;
                            break;
                        }
                    }
                }

                break;
            }
        }

        if (mQuestionBankCountDialog != null) {
            mQuestionBankCountDialog.dismiss();
            mQuestionBankCountDialog = null;
        }

        if (indexTemp == -1) {
            // 在所有问题中都不存在
            return;
        }
        if (index == -1) {
            for (Integer integer : mDataId) {
                if (integer == mSelectId) {
                    currentIndex = mDataId.indexOf(integer);
                }
            }
            // 在当前已加载的问题中不存在,先加载数据
            mSelectId = -1;
            loadOtherQuestion(indexTemp);

        }else {
            initText(mQuestionList.get(index),index);
            vpAnswer.setCurrentItem(index);
        }

        mSelectId = -1;

        isSelected = true;
    }

    private void loadNextQuestion(int index) {
        loadQuestion((index / 50 + 1) * 50,(mDataId.size() - (index / 50 + 1) * 50) <= 50 ? (mDataId.size() -  (index / 50 + 1) * 50) : 50);
    }

    private void loadOtherQuestion(int index) {
        loadQuestion((index / 50) * 50,(mDataId.size() - (index / 50) * 50) <= 50 ? (mDataId.size() -  (index / 50) * 50) : 50);
    }

    void loadQuestion(int index,int count) {
        mIndex = index;

        StringBuilder builder = new StringBuilder();
        for (int i = index ; i < index + count ; i ++) {
            builder.append(mDataId.get(i));
            builder.append(",");
        }
        if (builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }

        presenter.getQuestionBankContent(builder.toString());

    }

    private int mIndex = 0;
//    private int mCount = 0;

    void loadQuestion(List<Question> data) {
        for (int i = 0; i < data.size(); i++) {
            View view = View.inflate(this, R.layout.item_question, null);
            BridgeWebView webView = (BridgeWebView) view.findViewById(R.id.item_question_webview);
            WebViewManager webViewManager = new WebViewManager(this, webView);

            Question question = data.get(i);
            question.Text = question.getDecodedText(mSecretKey);
            question.QuestionAnalysis = question.getDecodedQuestionAnalysis(mSecretKey);
            for (Question.QuestionOption option : question.QuestionOptionList) {
                option.Content = option.getDecodedContent(mSecretKey);
            }

            answerListView.add(mIndex + i,view);
            answerListView.remove(mIndex + i + 1);
            mAnswerWebViewManagerList.add(mIndex + i,webViewManager);
            mAnswerWebViewManagerList.remove(mIndex + i + 1);
            mQuestionList.add(mIndex + i, data.get(i));
            mQuestionList.remove(mIndex + i + 1);
            this.data.add(mIndex + i,data.get(i));
            this.data.remove(mIndex + i + 1);
            mQuestionListSize ++;
        }


        detail.QuestionList = mQuestionList;
        detail.QuestionCount = mQuestionList.size();

        if (firstSelected) {
            if (mSelectId != -1) {
                answerAdapter2 = new QuestionAdapterForQuestionBank(answerListView,this.detail,mAnswerWebViewManagerList,mSecretKey,this);
                vpAnswer.setAdapter(answerAdapter2);
                showCertainQuestion();
                firstSelected = false;
            }else {
                if (vpAnswer.getAdapter() == null) {
                    answerAdapter2 = new QuestionAdapterForQuestionBank(answerListView,this.detail,mAnswerWebViewManagerList,mSecretKey,this);
                    vpAnswer.setAdapter(answerAdapter2);
                }else {
                    answerAdapter2.notifyDataSetChanged();
                }
                initText(this.data.get(currentIndex), currentIndex);
            }
        }else {
            initText(this.data.get(currentIndex), currentIndex);
            vpAnswer.setCurrentItem(currentIndex);
        }



    }

   public BridgeHandler mSubmitAnswerHandler = new BridgeHandler() {
        @Override
        public void handler(String json, CallBackFunction function) {
            try {
                String answerContent = new JSONObject(json).getString("AnswerContent");
                if (!TextUtils.isEmpty(answerContent)) {
                    if (currentIndex == mDataId.size() - 1) {
                        Utils.UI.showToastShort("已做到最后一题");
                    }
                    answerContents.add(vpAnswer.getCurrentItem(),answerContent);
                    if (answerContents.get(vpAnswer.getCurrentItem() + 1) == null) {
                        answerContents.remove(vpAnswer.getCurrentItem() + 1);
                    }
                    presenter.submitWrongQuestionAnswer(answerContent,mQuestionList.get(vpAnswer.getCurrentItem()).Id);
                }



            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    private int currentIndex = 0;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 123) {
                int currentItem = vpAnswer.getCurrentItem();

                if (currentItem != mQuestionBankList.Total - 1) {
                    isAnswerSubmit = true;
                    currentIndex = currentItem + 1;
                    vpAnswer.setCurrentItem(currentItem + 1);
                }
            }
        }
    };
}
